package Java8Test;

import java.util.function.Function;
import java.util.stream.Stream;

public class StreamTest5 {
    public static void main(String[] args) {

        System.out.println("Sequential sum done in:" +
                new StreamTest5().measureSumPerf(StreamTest5::sequentialSum, 10000000) + "msecs");
    }

    public long measureSumPerf(Function<Long, Long> adder, long n) {
        long fastest = Long.MAX_VALUE;
        for (int i = 0; i < 10; i++) {
            long start = System.nanoTime();
            long sum = adder.apply(n);
            long duration = (System.nanoTime() - start) / 1000000;
            System.out.println("Result：" + sum);
            if(duration < fastest) fastest = duration;
        }
        return fastest;
    }

    public static long sequentialSum(long n) {
        return Stream.iterate(1L, i -> i + 1)
                .limit(n)
                .reduce(0L, Long::sum);
    }


}
